package cn.crm.spring.service;

import cn.crm.spring.pojo.Customer;
import cn.crm.spring.pojo.User;
import cn.crm.spring.repository.CustomerRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service("CustomerService")
public class CustomerServiceImpl implements CustomerService {
    @Resource
    public CustomerRepository customerRepository;

    @Override
    public Page<Customer> findCustomerByCustName(String name, Pageable pageable) {
        Specification<Customer> specification = new Specification<Customer>() {

            @Override
            public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if (name != null && !name.equals("")) {
                    predicates.add(criteriaBuilder.like(root.get("custName"), "%" + name + "%"));
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        return customerRepository.findAll(specification, pageable);
    }

    @Override
    public Customer getId(Integer custId) {

        return customerRepository.findById(custId).get();
    }

    @Override
    public List<Customer> finAll() {
        return customerRepository.findAll();
    }
}
